import React, { useEffect } from "react";
import { useRoutes, useNavigate, useLocation } from "react-router-dom";
import routes from "@/router/route";
import { message } from "antd";

// 解析并验证token是否有效
function isTokenValid(token: string) {
  if (!token) return false;
  try {
    const payload = JSON.parse(atob(token.split(".")[1])); // 解码JWT的Payload部分
    const currentTime = Math.floor(Date.now() / 1000);
    return payload.exp > currentTime; // 检查是否过期
  } catch (error) {
    return false; // 如果解析失败，认为token无效
  }
}

function ToHome() {
  const navigataTo = useNavigate();
  useEffect(() => {
    navigataTo("/home/note");
    message.warning("已登录");
  }, []);
  return <div></div>;
}

function ToLogin() {
  const navigataTo = useNavigate();
  useEffect(() => {
    message.warning("未登录");
    navigataTo("/login");
  }, []);
  return <div></div>;
}

function BeferRoute() {
  const outlet = useRoutes(routes);
  const location = useLocation();
  // const accessToken = localStorage.getItem("Access-token");
  const refreshToken = localStorage.getItem("Refresh-token");
  const isValid = refreshToken ? isTokenValid(refreshToken) : false;
  //已登录，返回首页；未登录，返回登录注册页；登录过期，返回登录页
  if (location.pathname === "/login" && isValid) {
    return <ToHome />;
  } else if (
    location.pathname !== "/login" &&
    location.pathname !== "/registe" &&
    !isValid
  ) {
    return <ToLogin />;
  }
  return outlet;
}

const App: React.FC = () => {
  return (
    <div>
      <BeferRoute />
    </div>
  );
};

export default App;
